package net.lunjin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lunjin.util.Constants;

public class Filter301 implements Filter {
	
	protected String encoding = null;	
	
	protected FilterConfig filterConfig = null;
	
	protected boolean ignore = true;
	
	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		//String currUrl = "http://" + request.getServerName();//取得当前url
		//System.out.println("currUrl:" + currUrl);
		
		String redirectUrl = "";
		if ((!httpRequest.getServerName().startsWith("www."))&& 
			(httpRequest.getServerName().toLowerCase().indexOf("localhost")==-1)) {
			redirectUrl = Constants.URL;
			httpResponse.setStatus(301);
			httpResponse.setHeader("Location", redirectUrl);
			httpResponse.setHeader("Connection", "close");
			return;
		}
		//System.out.println("redirectUrl=" + redirectUrl);
		
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}
}